package com.inke.box.net.minasocket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.inke.box.utils.MinaNetWorkCanstant;
import com.orhanobut.hawk.Hawk;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * Created by Administrator on 2017/11/8.
 */

public class InkeMinaServer extends Service {

    private  int port = 10010;
    private boolean isConn = false;
    private SocketAcceptor acceptor ;
    private Thread workThread;
    private static InkeMinaServer inkeMinaServer;
    //启动成功失败回调
    private  MinaServerCallBack minaServerCallBack;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public InkeMinaServer setMinaServerCallBack(MinaServerCallBack scb) {
        this.minaServerCallBack = scb;
        return inkeMinaServer;
    }

    //返回实例
    public static InkeMinaServer getInstance(){
        return inkeMinaServer;
    }

    @Override
    public void onCreate() {
        super.onCreate();
       inkeMinaServer = this;
        //创建一个非阻塞的server端Socket ，用NIO
        acceptor = new NioSocketAcceptor();
        //创建接收数据的过滤器
        DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
        TextLineCodecFactory factory = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue() );
//        factory.setDecoderMaxLineLength(10 * 1024 * 1024);//(系统默认MyTextLineCodecFactory传输限制为1k，这里设置可以扩大传输，主要用于较大图片传输)
//        factory.setEncoderMaxLineLength(10 * 1024 * 1024);
        ProtocolCodecFilter filter= new ProtocolCodecFilter(factory);
        filterChain.addLast("codec", filter);
        //下面3个我是随便设置，为了试试能不能扩大MyTextLineCodecFactory的默认传输限制
        acceptor.getSessionConfig().setSendBufferSize(10 * 1024 * 1024);
        acceptor.getSessionConfig().setReadBufferSize(2048);
        acceptor.getSessionConfig().setReceiveBufferSize(10 * 1024 * 1024);
        //设定服务器消息处理器
        acceptor.setHandler(new InkeServerSocketHanlder());
        // 设置session配置，30秒内无操作进入空闲状态
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);

        //设定这个过滤器将以对象为单位读取数据
//        ProtocolCodecFilter filter = new ProtocolCodecFilter(new ObjectSerializationCodecFactory());
//        filterChain.addLast("objectFilter",filter);
//        acceptor.setHandler(new InkeServerSocketHanlder());

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    //端口累加 避免占用
    public void restStart() {
        port++;
        serverStart();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //服务器关闭
        if (acceptor!=null){
            acceptor.dispose();
        }
    }


    public void stopMinaServer(){
        //服务器关闭
        if (acceptor!=null){
            acceptor.dispose();
        }
    }


    //绑定启动服务
    public void serverStart(){
       workThread= new Thread(new MyRunnable());
       workThread.start();
    }

    class MyRunnable implements Runnable{

        @Override
        public void run() {
            try {
                //先取消绑定
                acceptor.unbind();
                //在绑定 避免冲突
                acceptor.bind(new InetSocketAddress(port));
                LogUtils.e("ServerSocket System go go go"+"-----本地ip:"+ NetworkUtils.getIPAddress(true)+"---Port--"+port);
                //存储服务器ip和端口号
                Hawk.put(MinaNetWorkCanstant.Local_Ip,acceptor.getLocalAddress());
                Hawk.put(MinaNetWorkCanstant.Local_Port,port);


                //回调结果
                if (minaServerCallBack!=null)
                   minaServerCallBack.onStarFinsh("ip__"+NetworkUtils.getIPAddress(true)+"_port_"+port);

            } catch (IOException e) {
                e.printStackTrace();
                LogUtils.e("ServerSocket 启动失败:"+e.getMessage());
                //启动失败 重启 切换端口 直到成功
                restStart();

            }
        }
    }

}
